package com.gxa.utils;



import com.gxa.pojo.Permission;

import java.util.ArrayList;
import java.util.List;


public class PowerTreeUtil {
    public static List<Permission> getTreeList(List<Permission> entityList) {
        List<Permission> resultList = new ArrayList<Permission>();

        //获取顶层元素集合
        Integer parentCode;
        for (Permission entity : entityList) {
            parentCode = entity.getPid();
            //顶层元素的parentCode==null或者为0
            if (parentCode == null || "0".equals(parentCode)) {
                resultList.add(entity);
            }
        }

        //获取每个顶层元素的子数据集合
        if (resultList.size() != 0) {
            for (Permission entity : resultList) {
                entity.setChildS(getSubList(entity.getPermissionID(), entityList));
            }
        }
        return resultList;
    }

    private static List<Permission> getSubList(Integer id, List<Permission> entityList) {
        List<Permission> childList = new ArrayList<Permission>();
        Integer parentId;

        //子集的直接子对象
        for (Permission entity : entityList) {
            parentId = entity.getPid();
            if (id.equals(parentId)) {
                childList.add(entity);
            }
        }

        //子集的间接子对象
        if (childList.size() != 0) {
            for (Permission entity : childList) {
                entity.setChildS(getSubList(entity.getPermissionID(), entityList));
            }
        }

        //递归退出条件
        if (childList.size() == 0) {
            return null;

        }

        return childList;

    }

}
